'use strict';

const fs = require('fs');
const config = require('./config');
const request = require('superagent');
const cheerio = require('cheerio');
const path = require('path');
const $q = require('q');

class Courses {
    constructor(lession_url) {
        this.lession_url = lession_url
    };

    test() {
    };

    async cousre() {
        try {
            let res = await this.parse_text(this.lession_url)
            let $ = cheerio.load(res.text)
            let hrefs = []
            $('article.course_list li a').each(function () {
                hrefs.push(`http://m.maiziedu.com${$(this).attr('href')}`)
            })
            return hrefs
        } catch (error) {
            if (error) {
                return console.log(`req the lession:${this.lession_url} is error`, error);
            }
        }
    };

    // 解析MP4地址
    async play(play_url) {
        let def = $q.defer()
        try {
            let res = await this.parse_text(play_url)
            let $ = cheerio.load(res.text)
            let play = $('video').attr('src')
            def.resolve(play)
        } catch (error) {
            def.resolve(new Error('parse mp4 err'))
        }
        return def.promise
    };

    // 获取某门课程下所有的视频地并存入文件
    async video(course_href) {
        try {
            let CourseObj = this
            let res = await CourseObj.parse_text(course_href)
            let $ = cheerio.load(res.text)
            $('article ol li a').each(async function () {
                let video_href = `http://m.maiziedu.com${$(this).attr('href')}`
                let play_name = $(this).text().match(/\d{2}:\d{2}(.+)/)[1]
                let play_href = await CourseObj.play(video_href)
                let play_item = {
                    title: $('title').text().split('-')[0],
                    course_href: course_href,
                    play_name: play_name,
                    play_href: play_href
                }
                let save = await CourseObj.save(play_item)
            })
        } catch (error) {
            if (error) {
                return console.log(`handler course_href:${course_href} is error`, error);
            }
        }
    };

    // 保存文件
    save(courseObj) {
        let def = $q.defer()
        fs.appendFile('../data/data.json', JSON.stringify(courseObj) + ",", err => {
            if (err) {
                def.reject(false)
            } else {
                def.resolve(true)
            }
        })
        return def.promise
    };

    // 整体请求连接，并返回promise
    parse_text(href) {
        return request.get(href).set(config.headers)
    };

}

module.exports = Courses


